package com.jinbei.common.util;

import com.alibaba.fastjson.JSONObject;
import com.jinbei.common.contants.Contants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @author zflu
 * Authorization 请求头解析
 * Created by lucky on 2018/7/19.
 */
public class AuthorizationUtil {

    private static final Logger logger = LoggerFactory.getLogger(AuthorizationUtil.class);

    /**
     * O O这是我的加盐
     */
    private static final String KEY = "luckyMao";

    /**
     * @author zflu
     * @Description   authorization base64加密
     * @date 2018/7/19 14:27
     * @param loginName 账号
     * @param password  密码
     * @return java.lang.String
     */
    public static String getAuthorization(String loginName , String password){
        StringBuffer buffer = new StringBuffer();
        long time = System.currentTimeMillis();
        buffer.append(KEY)
                .append(",")
                .append("loginName:")
                .append(loginName)
                .append(",")
                .append("password:")
                .append(password)
                .append(",")
                .append("time:")
                .append(time);
        return Base64.getEncoder().encodeToString(buffer.toString().getBytes());
    }
    
    /**   
     * @author zflu
     * @Description authorization base64解密
     * @date 2018/7/19 14:28  
     * @param code  解密码
     * @return com.alibaba.fastjson.JSONObject  
     */ 
    public static JSONObject getUserByAuthorization(String code){
        JSONObject json = new JSONObject();
        try {
            byte[] decode = Base64.getDecoder().decode(code.getBytes());
            String result = new String(decode, "UTF-8");
            String[] key = result.split(",");
            //如果加盐错误
            if(!KEY.equals(key[0])){
                return json;
            }
            String[] name = key[1].split(":");
            String[] password = key[2].split(":");
            String[] time = key[3].split(":");
            long keyTime = Long.valueOf(time[1]) + Contants.AUTHOR_USER_TIME;
            //授权失效 有效期24小时
            if(keyTime < System.currentTimeMillis()){
                return json;
            }
            json.put(password[0],password[1]);
            json.put(name[0],name[1]);
        } catch (UnsupportedEncodingException e) {
            logger.error("Authorization 解析失败........{}",e);
            e.printStackTrace();
            return json;
        }
        return json;
    }

    public static void main(String[] args) {
//        String authorization = getAuthorization("liming", "a18861856674");
//        System.out.println(authorization);
//        String code = "bHVja3lNYW8sbG9naW5OYW1lOnhpYW9taW5nLHBhc3N3b3JkOkUxMEFEQzM5NDlCQTU5QUJCRTU2RTA1N0YyMEY4ODNFMDEyRlFBVzMyMSx0aW1lOjE1MzMxMTA3OTY2NjA=";
//        JSONObject json = getUserByAuthorization(code);
//        System.out.println(json.toJSONString());
    }
}
